package beans;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;

import model.User;

/**
 * Session Bean implementation class UserSync
 */
@Stateless
@LocalBean
public class UserSync implements UserSyncLocal {

    /**
     * Default constructor. 
     */
	@Resource(mappedName = "java:/topic/mojTopic2")
    Topic topic;
	
	@Resource(mappedName = "java:/ConnectionFactory")
	ConnectionFactory connectionFactory;
	
	private TopicConnection connection;

	private TopicPublisher publisher;

	private TopicSession session;
	
    public UserSync() {
        // TODO Auto-generated constructor stub
    }

	private void connect() throws JMSException {
		// TODO Auto-generated method stub
			connection = (TopicConnection)connectionFactory.createConnection("guest", "guestguest");
			session = connection.createTopicSession(false,
			        Session.AUTO_ACKNOWLEDGE);
			connection.start();
	}

	private void disconnect() throws JMSException {
		publisher.close();
		connection.stop();
		connection.close();
		session.close();
	}

	@Override
	public void syncWithClient(User user) {
		// TODO Auto-generated method stub
		// create and publish a message
		try {
			connect();
			ObjectMessage msg = session.createObjectMessage(user);
			publisher = session.createPublisher(topic);
			publisher.publish(msg);
			disconnect();
			
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
					
	}

	@Override
	public void syncWithClient(List<User> users) {
		// TODO Auto-generated method stub
		try {
			connect();
			publisher = session.createPublisher(topic);
			for(User user : users) {
				ObjectMessage msg = session.createObjectMessage(user);
				publisher.publish(msg);
			}
			disconnect();
			
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    

}
